<template>
    <div class="notification-popup">
        <el-popover placement="bottom-end" :width="400" trigger="hover" popper-class="notification-popover"
            @show="handleShow" @hide="handleHide">
            <template #reference>
                <div class="notification-trigger">
                    <el-icon class="notification-icon">
                        <Bell />
                    </el-icon>
                    <el-badge v-if="unreadCount > 0" :value="unreadCount > 99 ? '99+' : unreadCount"
                        class="notification-badge" :hidden="unreadCount === 0" />
                </div>
            </template>

            <div class="notification-content">
                <div class="notification-header">
                    <h3 class="notification-title">系统通知</h3>
                    <div class="notification-actions">
                        <el-button v-if="unreadCount > 0" type="primary" size="small" @click="markAllAsRead"
                            :loading="markAllLoading">
                            全部标已读
                        </el-button>
                        <el-button type="text" size="small" @click="refreshNotifications" :loading="loading">
                            <el-icon>
                                <Refresh />
                            </el-icon>
                        </el-button>
                    </div>
                </div>

                <div class="notification-tabs">
                    <div class="notification-list">
                        <div v-for="notification in filteredNotifications" :key="notification.id"
                            class="notification-item" :class="{ 'unread': !notification.readed }"
                            @mouseenter="handleItemHover(notification)" @mouseleave="handleItemLeave">
                            <div class="notification-content-wrapper">
                                <div class="notification-main">
                                    <div class="notification-title-text">{{ notification.msg }}</div>
                                    <div class="notification-desc">{{ notification.content }}</div>
                                    <div class="notification-time">{{ formatTime(notification.created_at) }}</div>
                                </div>
                                <div class="notification-actions-item">
                                    <el-button style="margin-bottom: 10px;"
                                        v-if="!notification.readed && hoveredNotification?.id === notification.id"
                                        type="primary" size="small" @click="markAsRead(notification.id)"
                                        :loading="markLoading === notification.id">
                                        标已读
                                    </el-button>
                                    <el-button type="text" size="small" @click="deleteNotification(notification.id)"
                                        :loading="deleteLoading === notification.id">
                                        <el-icon>
                                            <Delete />
                                        </el-icon>
                                    </el-button>
                                </div>
                            </div>
                        </div>

                        <div v-if="filteredNotifications.length === 0" class="empty-state">
                            <el-empty description="暂无通知" />
                        </div>
                    </div>
                </div>

                <div class="notification-footer">
                    <el-button type="text" size="small" @click="viewAllNotifications">
                        查看全部通知
                    </el-button>
                </div>
            </div>
        </el-popover>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Bell, Refresh, Delete } from '@element-plus/icons-vue'
import { getMsgList, readed, deleteNotificationApi } from '@/api/notification'

interface Notification {
    id: number | string
    msg: string
    content: string
    readed: number
    created_at: string
    updated_at: string
}

const loading = ref(false)
const markAllLoading = ref(false)
const markLoading = ref<number | string | null>(null)
const deleteLoading = ref<number | string | null>(null)
const activeTab = ref('all')
const notifications = ref<Notification[]>([])
const unreadCount = ref(0)
const hoveredNotification = ref<Notification | null>(null)

// 计算属性
const unreadNotifications = computed(() => {
    return notifications.value.filter(item => !item.readed)
})

const filteredNotifications = computed(() => {
    return notifications.value
})

// 处理显示
const handleShow = () => {
    fetchNotifications()
    // fetchUnreadCount()
}

// 处理隐藏
const handleHide = () => {
    hoveredNotification.value = null
}

// 处理标签页切换
const handleTabChange = (tab: string | number) => {
    activeTab.value = tab as string
}

// 处理项目hover
const handleItemHover = (notification: Notification) => {
    hoveredNotification.value = notification
}

// 处理项目离开
const handleItemLeave = () => {
    hoveredNotification.value = null
}

// 获取通知列表
const fetchNotifications = async () => {
    try {
        loading.value = true
        const response = await getMsgList({
            page_no: 1,
            page_size: 20
        })
        notifications.value = response.lists || []
        unreadCount.value = response.unread_total
        console.log(notifications.value, 'notifications.valuenotifications.value');

    } catch (error) {
        console.error('获取通知列表失败:', error)
        // ElMessage.error('获取通知列表失败')
    } finally {
        loading.value = false
    }
}

fetchNotifications()

// // 获取未读数量
// const fetchUnreadCount = async () => {`
//     try {
//         const response = await getUnreadNotificationCount()
//         unreadCount.value = response.count || 0
//     } catch (error) {
//         console.error('获取未读数量失败:', error)
//     }
// }

// 删除通知
const deleteNotification = async (notificationId: number | string) => {
    try {
        await ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })

        deleteLoading.value = notificationId
        await deleteNotificationApi({ id: notificationId })

        fetchNotifications()

    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除通知失败:', error)
            ElMessage.error('删除通知失败')
        }
    } finally {
        deleteLoading.value = null
    }
}


// 标记为已读
const markAsRead = async (notificationId: number | string) => {
    console.log(notificationId, 'notificationIdnotificationIdnotificationId');
    try {
        markLoading.value = notificationId
        console.log(notificationId, 'notificationIdnotificationIdnotificationId');

        await readed({ id: notificationId })

        // 更新未读数量
        await fetchNotifications()

        ElMessage.success('已标记为已读')
    } catch (error) {
        console.error('标记已读失败:', error)
        ElMessage.error('标记已读失败')
    } finally {
        markLoading.value = null
    }
}

// 全部标已读
const markAllAsRead = async () => {
    try {
        markAllLoading.value = true
        // await markAllNotificationsAsRead()

        // 更新本地状态
        notifications.value.forEach(item => {
            item.readed = 1
        })

        // 更新未读数量
        // await fetchUnreadCount()

        await readed({ all: 1 })

        ElMessage.success('已全部标记为已读')
    } catch (error) {
        console.error('全部标记已读失败:', error)
        ElMessage.error('全部标记已读失败')
    } finally {
        markAllLoading.value = false
    }
}


// 刷新通知
const refreshNotifications = () => {
    fetchNotifications()
}

import { useRouter } from 'vue-router'

const router = useRouter()

// 查看全部通知
const viewAllNotifications = () => {
    router.push('/notification')
}


// 格式化时间
const formatTime = (timeStr: string) => {
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now.getTime() - date.getTime()

    const minutes = Math.floor(diff / (1000 * 60))
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(diff / (1000 * 60 * 60 * 24))

    if (minutes < 1) {
        return '刚刚'
    } else if (minutes < 60) {
        return `${minutes}分钟前`
    } else if (hours < 24) {
        return `${hours}小时前`
    } else if (days < 7) {
        return `${days}天前`
    } else {
        return date.toLocaleDateString()
    }
}

// 定时刷新未读数量
let refreshTimer: number | null = null

onMounted(() => {
    // // 初始获取未读数量
    // fetchUnreadCount()

    // // 每30秒刷新一次未读数量
    // refreshTimer = setInterval(() => {
    //     fetchUnreadCount()
    // }, 30000)
})

onUnmounted(() => {
    if (refreshTimer) {
        clearInterval(refreshTimer)
    }
})
</script>

<style lang="scss" scoped>
.notification-popup {
    .notification-trigger {
        position: relative;
        cursor: pointer;
        padding: 8px;
        border-radius: 4px;
        transition: background-color 0.3s;
        display: flex;
        align-items: center;
        justify-content: center;
        min-width: 36px;
        min-height: 36px;

        &:hover {
            background-color: rgba(0, 0, 0, 0.05);
        }

        .notification-icon {
            font-size: 20px;
            color: #606266;
            line-height: 1;
        }

        .notification-badge {
            position: absolute;
            top: 4px;
            right: 4px;
            transform: scale(0.8);
            z-index: 10;
        }
    }
}

.notification-content {
    .notification-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 16px 0;
        // border-bottom: 1px solid #f0f0f0;
        margin-bottom: 10px;
        padding-right: 0px;

        .notification-title {
            margin: 0;
            font-size: 16px;
            font-weight: 600;
            color: #303133;
        }

        .notification-actions {
            display: flex;
            gap: 8px;
        }
    }

    .notification-tabs {
        .notification-list {
            max-height: 400px;
            overflow-y: auto;

            .notification-item {
                padding: 12px 16px;
                padding-left: 20px;
                border-bottom: 1px solid #f5f5f5;
                transition: background-color 0.3s;

                &:hover {
                    background-color: #f8f9fa;
                }

                &.unread {
                    position: relative;

                    &:hover {
                        background-color: #e6f7ff;
                    }
                }

                &.unread::before {
                    content: '';
                    display: block;
                    width: 8px;
                    height: 8px;
                    border-radius: 50%;
                    background: #1890ff;
                    position: absolute;
                    left: 5px;
                    top: 50%;
                    transform: translateY(-50%);
                    z-index: 1;
                }

                .notification-content-wrapper {
                    display: flex;
                    justify-content: space-between;
                    align-items: flex-start;
                    gap: 12px;

                    .notification-main {
                        flex: 1;
                        min-width: 0;

                        .notification-title-text {
                            font-weight: 500;
                            color: #303133;
                            margin-bottom: 4px;
                            line-height: 1.4;
                        }

                        .notification-desc {
                            color: #606266;
                            font-size: 13px;
                            line-height: 1.4;
                            margin-bottom: 4px;
                            display: -webkit-box;
                            -webkit-line-clamp: 2;
                            -webkit-box-orient: vertical;
                            overflow: hidden;
                        }

                        .notification-time {
                            color: #909399;
                            font-size: 12px;
                        }
                    }

                    .notification-actions-item {
                        display: flex;
                        flex-direction: column;
                        gap: 4px;
                        flex-shrink: 0;
                    }
                }
            }

            .empty-state {
                padding: 40px 0;
                text-align: center;
            }
        }
    }

    .notification-footer {
        padding: 12px 16px;
        border-top: 1px solid #f0f0f0;
        text-align: center;
    }
}

// 全局样式
:global(.notification-popover) {
    padding: 0;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>